package cn.vehicle.exception;

import cn.vehicle.domains.vo.Result;
import cn.vehicle.enums.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(VehicleAccessException.class)
    public Result<Void> vehicleAccessExceptionHandler(VehicleAccessException e) {
        return Result.error(e.getDefineCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> exceptionHandler(Exception e) {
        log.error("出现系统异常", e);
        return Result.error(StatusCode.SYSTEM_ERROR.getCode(), StatusCode.SYSTEM_ERROR.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        Map<String, String> errors = new HashMap<>();

        e.getBindingResult().getAllErrors().forEach((error) -> {
            String field = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();

            errors.put(field, errorMessage);
        });

        return Result.error(StatusCode.PARAMS_ERROR.getCode(), "请求参数验证失败" + errors);
    }
}
